package com.snail.utils;

import com.alibaba.dashscope.audio.asr.translation.TranslationRecognizerParam;
import com.alibaba.dashscope.audio.asr.translation.TranslationRecognizerRealtime;
import com.alibaba.dashscope.audio.asr.translation.results.TranslationRecognizerResult;
import com.alibaba.dashscope.common.ResultCallback;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import static com.snail.utils.SubtitleEntry.formatTimestamp;

public class RealtimeTranslateTask implements Runnable {
    private final Path filepath;
    private final TranscriptionResultCallback callback;

    public RealtimeTranslateTask(Path filepath, TranscriptionResultCallback callback) {
        this.filepath = filepath;
        this.callback = callback;
    }

    @Override
    public void run() {
        // https://help.aliyun.com/document_detail/2712536.html
        TranslationRecognizerParam param =
                TranslationRecognizerParam.builder()
                        // 若没有将API Key配置到环境变量中，需将your-api-key替换为自己的API Key
                        // .apiKey("your-api-key")
                        .model("gummy-realtime-v1")
                        .format("pcm") // 'pcm'、'wav'、'mp3'、'opus'、'speex'、'aac'、'amr', you
                        // can check the supported formats in the document
                        .sampleRate(16000)
                        .transcriptionEnabled(true)
                        .sourceLanguage("auto")
                        .translationEnabled(false)
                        .build();
        TranslationRecognizerRealtime recognizer = new TranslationRecognizerRealtime();
        List<SubtitleEntry> subtitles = new ArrayList<>();
        AtomicInteger subtitleIndex = new AtomicInteger(1);
        ResultCallback<TranslationRecognizerResult> resultCallback =
                new ResultCallback<TranslationRecognizerResult>() {
                    @Override
                    public void onEvent(TranslationRecognizerResult result) {
                        if (result.isSentenceEnd()) {
                            String text = result.getTranscriptionResult().getText();
                            Long beginTime = result.getTranscriptionResult().getBeginTime();
                            Long endTime = result.getTranscriptionResult().getEndTime();
                            if (beginTime != null && endTime != null) {
                                SubtitleEntry entry = new SubtitleEntry(
                                        subtitleIndex.getAndIncrement(),
                                        formatTimestamp(beginTime),
                                        formatTimestamp(endTime),
                                        text
                                );
                                // System.out.println(entry + "\n\n");
                                subtitles.add(entry);
                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        // 拼接完整的SRT内容
                        StringBuilder stringBuilder = new StringBuilder();
                        for (SubtitleEntry entry : subtitles) {
                            stringBuilder.append(entry).append("\n\n");
                        }
                        // 打印或保存到文件
//                        System.out.println("======== 生成的SRT字幕内容 =========");
//                        System.out.println(stringBuilder);
                        // 回调返回结果
                        if (callback != null) {
                            callback.onResult(stringBuilder.toString());
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                };



        // 这一步只是把参数和回调函数绑定到translator,并未真正发起调用
        recognizer.call(param, resultCallback);
        try (FileInputStream fis = new FileInputStream(this.filepath.toFile())) {
            // chunk size set to 1 seconds for 16KHz sample rate
            byte[] buffer = new byte[3200];
            int bytesRead;
            // Loop to read chunks of the file
            while ((bytesRead = fis.read(buffer)) != -1) {
                ByteBuffer byteBuffer;
                if (bytesRead < buffer.length) {
                    byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
                } else {
                    byteBuffer = ByteBuffer.wrap(buffer);
                }
                // 这里才真正把块发送给服务器
                recognizer.sendAudioFrame(byteBuffer);
                buffer = new byte[3200];
                // Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        recognizer.stop();
    }
}